package com.apobates.forum.thrones.admin.controller;

import com.apobates.forum.core.ImageIOMeta;
import com.apobates.forum.core.entity.BoardCarouselIndex;
import com.apobates.forum.core.entity.TopicCarousel;
import com.apobates.forum.core.entity.TopicCarouselSlide;
import com.apobates.forum.core.service.TopicCarouselService;
import com.apobates.forum.core.service.TopicCarouselSlideService;
import com.apobates.forum.member.entity.ForumCalendarUnitEnum;
import com.apobates.forum.member.storage.core.MemberSessionBean;
import com.apobates.forum.thrones.admin.controller.form.BoardCarouselForm;
import com.apobates.forum.thrones.admin.controller.form.TopicCarouselForm;
import com.apobates.forum.thrones.admin.controller.form.TopicCarouselSlideForm;
import com.apobates.forum.thrones.admin.controller.helper.AdminUtils;
import com.apobates.forum.utils.TipMessage;
import com.apobates.forum.utils.lang.EnumArchitecture;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 *
 * @author xiaofanku
 * @since 20200614
 */
@Controller
@RequestMapping(value = "/topic/carousel")
public class AdminTopicCarouselController {
    @Autowired
    private TopicCarouselService topicCarouselService;
    @Autowired
    private TopicCarouselSlideService topicCarouselSlideService;
    @Autowired
    private ImageIOMeta imageIOMeta;
    private final static Logger logger = LoggerFactory.getLogger(AdminTopicCarouselController.class);
    
    //忽略状态的所有轮播图
    @GetMapping(path = "/")
    public String listPage(HttpServletRequest request, Model model) {
        model.addAttribute("rs", topicCarouselService.getAll().collect(Collectors.toList()));
        return "admin/topic_carousel/index";
    }
    //编辑或创建轮播图
    @GetMapping(path = "/edit")
    public String editEditForm(@RequestParam(name = "id", required = false, defaultValue = "0") int id, HttpServletRequest request, Model model) {
        TopicCarouselForm form = new TopicCarouselForm();
        TopicCarousel tc = topicCarouselService.get(id).orElse(TopicCarousel.empty());
        form.setRecord(tc.getId());
        form.setStatus(tc.isStatus());
        form.setTitle(tc.getTitle());
        form.setSummary(tc.getSummary());
        model.addAttribute("form", form);
        model.addAttribute("paramId", id);
        return "admin/topic_carousel/edit";
    }
    @PostMapping(path = "/edit")
    public String editEditAction(
            HttpServletRequest request, 
            @Valid @ModelAttribute("form") TopicCarouselForm form,
            BindingResult bindingResult,
            Model model) {
        if (bindingResult.hasErrors()) {
            model.addAttribute("form", form);
            return "admin/topic_carousel/edit";
        }
        String ctitle = form.getTitle();
        if (!AdminUtils.isAlphaNumeric(ctitle)) {
            model.addAttribute("errors", "非法的标题名称,只允许字母和数字组合,不可以使用中文");
            model.addAttribute("form", form);
            return "admin/topic_carousel/edit";
        }
        boolean symbol;
        if (form.isUpdate()) {
            symbol = topicCarouselService.edit(form.getIntegerRecord(), ctitle, form.getSummary(), form.getBooleanStatus()).orElse(false);
        } else {
            int data = topicCarouselService.create(ctitle, form.getSummary(), form.getBooleanStatus());
            symbol = data > 0;
            if (symbol) {
                form.setRecord(data);
            }
        }
        if (symbol) {
            //新增:跳转到增加幻灯片
            //编辑:
            return (form.isUpdate()) ? "redirect:/topic/carousel/" : "redirect:/topic/carousel/slide/edit?carousel=" + form.getRecord();
        }
        model.addAttribute("errors", form.getActionTitle() + "轮播图操作失败");
        model.addAttribute("form", form);
        return "admin/topic_carousel/edit";
    }
    //删除remove
    @PostMapping(path = "/remove", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public TipMessage removeTopicCarouselAction(
            @RequestParam("id") int topicCarouselId,
            MemberSessionBean mbean,
            HttpServletRequest request,
            Model model) {
        return TipMessage.Builder.take(()->topicCarouselService.remove(topicCarouselId)).success("轮播图删除成功").error("操作失败");
    }
    //轮播图下所有幻灯片,忽略状态
    @GetMapping(path = "/slide")
    public String getAllSlidePage(@RequestParam("carousel") int topicCarouselId, HttpServletRequest request, Model model) {
        model.addAttribute("rs", topicCarouselSlideService.getAllIgnoreStatus(topicCarouselId).collect(Collectors.toList()));
        return "admin/topic_carousel/slide_index";
    }
    //编辑或创建幻灯片
    @GetMapping(path = "/slide/edit")
    public String slideEditForm(
            @RequestParam(name = "id", required = false, defaultValue = "0") int carouselSlideId,
            @RequestParam(name = "carousel", required = false, defaultValue = "0") int carouselId,
            HttpServletRequest request,
            Model model) {
        TopicCarouselSlideForm form = new TopicCarouselSlideForm();
        TopicCarouselSlide tcs = topicCarouselSlideService.get(carouselSlideId).orElse(TopicCarouselSlide.empty(carouselId));
        form.setRecord(tcs.getId());
        form.setStatus(tcs.isStatus());
        form.setTitle(tcs.getTitle());
        form.setLink(tcs.getLink());
        form.setRanking(tcs.getRanking() + "");
        form.setCarousel(tcs.getTopicCarouselId() + "");
        form.setImageAddr(tcs.getImageAddr());
        if (carouselSlideId == 0 && carouselId > 0) { //为轮播图增加幻灯片
            form.setCarousel(carouselId + "");
        }
        model.addAttribute("form", form);
        return "admin/topic_carousel/slide_edit";
    }
    
    @PostMapping(path = "/slide/edit")
    public String slideEditAction(
            HttpServletRequest request,
            @Valid @ModelAttribute("form") TopicCarouselSlideForm form,
            BindingResult bindingResult,
            Model model) {
        if (bindingResult.hasErrors()) {
            model.addAttribute("form", form);
            return "admin/topic_carousel/slide_edit";
        }
        boolean symbol=false;
        if (form.isUpdate()) {
            symbol = topicCarouselSlideService.edit(form.getIntegerRecord(), form.getTitle(), form.getLink(), form.getIntegerRanking(), form.getBooleanStatus()).orElse(false);
        } else {
            //------------------------------------------------------------编码图标图片的地址
            String icoImageAddr = form.getEncodePictureAddr(imageIOMeta).orElse(null);
            //------------------------------------------------------------
            if(null != icoImageAddr){
                symbol = topicCarouselSlideService.create(form.getIntegerCarousel(), form.getTitle(), form.getLink(), icoImageAddr, form.getIntegerRanking(), form.getBooleanStatus())>0;
            }
        }
        if (symbol) {
            return "redirect:/topic/carousel/slide?carousel=" + form.getCarousel();
        }
        model.addAttribute("errors", form.getActionTitle() + "幻灯片操作失败");
        model.addAttribute("form", form);
        return "admin/topic_carousel/slide_edit";
    }
    //删除remove
    @PostMapping(path = "/slide/remove", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public TipMessage removeTopicCarouselSlideAction(
            @RequestParam("id") int topicCarouselSlideId,
            @RequestParam("carousel") int topicCarouselId,
            MemberSessionBean mbean,
            HttpServletRequest request,
            Model model) {
        return TipMessage.Builder.take(()->topicCarouselSlideService.remove(topicCarouselSlideId, topicCarouselId)).success("幻灯片删除成功").error("操作失败");
    }
    //版块绑定轮播图
    @GetMapping(path = "/bind")
    public String bindBoardForm(
            @RequestParam("carousel") int topicCarouselId,
            HttpServletRequest request,
            Model model) {
        BoardCarouselForm form = new BoardCarouselForm();
        form.setBoardId("0");
        form.setVolumesId("-1");
        form.setLimit("1");
        form.setUnit("3");
        form.setCarouselId(topicCarouselId + "");
        model.addAttribute("form", form);
        TopicCarousel tc = topicCarouselService.get(topicCarouselId).orElse(TopicCarousel.empty());
        model.addAttribute("carousel", tc);
        return "admin/topic_carousel/bind";
    }
    @PostMapping(path = "/bind")
    public String bindBoardAction(
            @ModelAttribute("form") BoardCarouselForm form,
            HttpServletRequest request,
            Model model) {
        boolean symbol = topicCarouselService.bindBoard(form.getIntegerVolumes(), form.getLongBoard(), form.getIntegerCarousel(), form.getDateTimeExpireDate()).orElse(false);
        if (symbol) {
            return "redirect:/topic/carousel/bind/result?carousel=" + form.getCarouselId();
        }
        model.addAttribute("errors", "版块绑定轮播图操作失败");
        model.addAttribute("form", form);
        TopicCarousel tc = topicCarouselService.get(form.getIntegerCarousel()).orElse(TopicCarousel.empty());
        model.addAttribute("carousel", tc);
        return "admin/topic_carousel/bind";
    }
    @PostMapping(path = "/bind/remove", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public TipMessage removebindBoardRecordAction(
            @RequestParam("carousel") int topicCarouselId,
            @RequestParam("board") long boardId,
            @RequestParam("volumes") int volumesId,
            HttpServletRequest request,
            Model model) {
        return TipMessage.Builder.take(()->topicCarouselService.remove(topicCarouselId, volumesId, boardId)).success("版块轮播图关联删除成功").error("操作失败");
    }
    
    //版块绑定轮播图记录
    @GetMapping(path = "/bind/result")
    public String bindBoardPage(
            @RequestParam("carousel") int topicCarouselId,
            HttpServletRequest request,
            Model model) {
        List<BoardCarouselIndex> rs = topicCarouselService.getAllRelative(topicCarouselId).collect(Collectors.toList());
        model.addAttribute("rs", rs);
        return "admin/topic_carousel/bind_result";
    }
    
    //绑定轮播图时长单位
    @GetMapping(path = "/bind/unit/json", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Map<Integer, String> getAllTimeUnit(HttpServletRequest request, Model model) {
        return EnumArchitecture.getInstance(ForumCalendarUnitEnum.class).entrySet().stream().filter(x -> x.getKey() > 2).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    }
}